package com.zhhs.jzcd.sms;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zhhs.common.exception.ServiceException;
import com.zhhs.common.utils.StringUtils;
import com.zhhs.common.utils.Threads;
import com.zhhs.jzcd.sms.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @description: 短信平台API实现
 * @author: JiaLe
 * @date: 2023-06-30 14:41
 **/
@Slf4j
@Service
public class SmsService {
    /**
     * 相同短信内容群发
     * @param marketingId  营销数据id
     * @param msg  短信内容
     * @param phone  电话号码  逗号隔开  17791859648,15802839421
     * @return
     */
    public void contentMassPosting(Long marketingId,String msg, String phone) {
        if (StringUtils.isBlank(msg)||StringUtils.isBlank(phone)){
            throw  new ServiceException("短信内容为空|手机号码为空");
        }
        Threads.SINGLE_THREAD_POOL.execute(new Runnable() {
            @Override
            public void run() {
                String url ="sms/batch/v1";
                JSONObject jsonObject = createJson();
                jsonObject.put("phone",phone);
                jsonObject.put("msg",msg);
                jsonObject.put("extend","");
                String body = buildRequest(url).body(jsonObject.toJSONString()).execute().body();
                checkResult(marketingId,body);
            }
        });
    }

    //=============================公共部分==========================================
    private static HttpRequest buildRequest(String url) {
        return HttpRequest.post(SmsConfig.baseUrl+url).header("Content-Type", "application/json;charset=UTF-8");
    }

    //添加基本信息
    private static JSONObject createJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appkey", SmsConfig.appkey);
        jsonObject.put("appcode", SmsConfig.appsecret);
        String timestamp = System.currentTimeMillis()+"";
        jsonObject.put("timestamp",timestamp);
        //生成sign签名
        String sign = createSign(SmsConfig.appkey, SmsConfig.appsecret, timestamp);
        jsonObject.put("sign",sign);
        return jsonObject;
    }

    /**
     * 生成签名
     * @param appkey
     * @param appsecret
     * @param timestamp
     * @return
     */
    private static String createSign(String appkey, String appsecret, String timestamp){
        StringBuffer str =new StringBuffer();
        String s = str.append(appkey).append(appsecret).append(timestamp).toString();
        try {
            return md5(s);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static String md5(String param) throws  UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Byte = md5.digest(param.getBytes("utf8"));
        String result = byteToHex(md5Byte);
        return result;
    }

    private static String byteToHex(byte[] md5Byte) {
        String result = "";
        StringBuilder sb = new StringBuilder();
        for(byte each : md5Byte){
            int value = each&0xff;
            String hex = Integer.toHexString(value);
            if(value<16){
                sb.append("0");
            }
            sb.append(hex);
        }
        result = sb.toString();
        return result;
    }

    /**
     * 判断结果处理信息记录功能
     */
    public void checkResult(Long marketingId,String body){
        //判断结果 异步记录群发内容
        JSONObject jsonObject = JSON.parseObject(body);
        String code = jsonObject.get("code").toString();
        if (code.equals(SmsConstant.SUCCESS_CODE)){
            String result = jsonObject.get("result").toString();
            List<ResultVo> resultVoList = JSONArray.parseArray(result, ResultVo.class);
            resultVoList.stream().forEach(s-> {
                s.setMarketingId(marketingId);
                s.setPhone(s.getPhone());
            });
            //批量入库

        }
    }
}
